﻿"use strict";
$jq.namespace('PeopleMedia.CP');

PeopleMedia.CP.ProfileManager = function () {
    this._siteId = PeopleMedia.CP.SiteID();
    this._includedQuestions = [];
    this._excludedQuestions = [];
    this._questions = [];
    this._initialQuestions = [];
    this._standardQuestions = [];
    this._questionTextOverride = {};
    this._responseTextOverride = {};
    this._responseExclusions = {};
    this._profilePanelId = "divProfile";
    this._questionContainerId = "divProfileQuestions";
    this._questionTemplateId = "divProfileQuestionTemplate";
    this._responseFieldnamePrefix = "ddlProfileResponse_";
    this._busyClassname = "busy";
    this._onQuestionsLoaded = null;
    this._onQuestionDisplay = null;
    this._onQuestionsPreSubmit = null;
    this._onQuestionsSubmitted = null;
    this._currentPanelNumber = 1;
    this._panelCount = 1;
    this._defaultOptionListType = this.OPTION_LIST_TYPE_DROPDOWN;
    this.OPTION_LIST_TYPE_DROPDOWN = 0;
    this.OPTION_LIST_TYPE_LIST = 1;
    this.OPTION_LIST_TYPE_DIV = 2;
    this._maxListViewSize = 10;
    this._addChooseOptionToResponses = true;
    this._nextPage = null;
    this._gotoSiteWhenDone = false;

    PeopleMedia.CP.ProfileManager._instance = this;
};

PeopleMedia.CP.ProfileManager._instance = null;
PeopleMedia.CP.ProfileManager.getInstance = function () {
    return PeopleMedia.CP.ProfileManager._instance;
};

PeopleMedia.CP.ProfileManager.prototype = {
    Oid: "PeopleMedia.CP.ProfileManager",
    SiteId: function (siteId) {
        if (arguments.length > 0) {
            this._siteId = siteId;
        } else {
            return this._siteId;
        }
    },
    IncludedQuestions: function (includedQuestions) {
        if (arguments.length > 0) {
            this._includedQuestions = includedQuestions;
        } else {
            return this._includedQuestions;
        }
    },
    ExcludedQuestions: function (excludedQuestions) {
        if (arguments.length > 0) {
            this._excludedQuestions = excludedQuestions;
        } else {
            return this._excludedQuestions;
        }
    },
    Questions: function () {
        return this._questions;
    },
    StandardQuestions: function () {
        return this._standardQuestions;
    },
    InitialQuestions: function (initialQuestions) {
        if (arguments.length > 0) {
            this._initialQuestions = initialQuestions;
        } else {
            return this._initialQuestions;
        }
    },
    ProfilePanelId: function (profilePanelId) {
        if (arguments.length > 0) {
            this._profilePanelId = profilePanelId;
        } else {
            return this._profilePanelId;
        }
    },
    ProfilePanel: function () {
        return $jq("#" + this._profilePanelId);
    },
    QuestionContainerId: function (questionContainerId) {
        if (arguments.length > 0) {
            this._questionContainerId = questionContainerId;
        } else {
            return this._questionContainerId;
        }
    },
    QuestionTemplateId: function (questionTemplateId) {
        if (arguments.length > 0) {
            this._questionTemplateId = questionTemplateId;
        } else {
            return this._questionTemplateId;
        }
    },
    ResponseFieldnamePrefix: function (responseFieldnamePrefix) {
        if (arguments.length > 0) {
            this._responseFieldnamePrefix = responseFieldnamePrefix;
        } else {
            return this._responseFieldnamePrefix;
        }
    },
    BusyClassname: function (busyClassname) {
        if (arguments.length > 0) {
            this._busyClassname = busyClassname;
        } else {
            return this._busyClassname;
        }
    },
    OnQuestionsLoaded: function (onQuestionsLoaded) {
        if (arguments.length > 0) {
            this._onQuestionsLoaded = onQuestionsLoaded;
        } else {
            return this._onQuestionsLoaded;
        }
    },
    OnQuestionDisplay: function (onQuestionDisplay) {
        if (arguments.length > 0) {
            this._onQuestionDisplay = onQuestionDisplay;
        } else {
            return this._onQuestionDisplay;
        }
    },
    OnQuestionsPreSubmit: function (onQuestionsPreSubmit) {
        if (arguments.length > 0) {
            this._onQuestionsPreSubmit = onQuestionsPreSubmit;
        } else {
            return this._onQuestionsPreSubmit;
        }
    },
    OnQuestionsSubmitted: function (onQuestionsSubmitted) {
        if (arguments.length > 0) {
            this._onQuestionsSubmitted = onQuestionsSubmitted;
        } else {
            return this._onQuestionsSubmitted;
        }
    },
    CurrentPanelNumber: function () {
        return this._currentPanelNumber;
    },
    PanelCount: function (panelCount) {
        if (arguments.length > 0) {
            this._panelCount = panelCount;
        } else {
            return this._panelCount;
        }
    },
    DefaultOptionListType: function (defaultOptionListType) {
        if (arguments.length > 0) {
            this._defaultOptionListType = defaultOptionListType;
        } else {
            return this._defaultOptionListType;
        }
    },
    MaxListViewSize: function (maxListViewSize) {
        if (arguments.length > 0) {
            this._maxListViewSize = maxListViewSize;
        } else {
            return this._maxListViewSize;
        }
    },
    AddChooseOptionToResponses: function (addChooseOptionToResponses) {
        if (arguments.length > 0) {
            this._addChooseOptionToResponses = addChooseOptionToResponses;
        } else {
            return this._addChooseOptionToResponses;
        }
    },
    NextPage: function (nextPage) {
		alert("NextPageApplica");
        if (arguments.length > 0) {
            this._nextPage = nextPage;
        } else {
            return this._nextPage;
        }
    },
    GotoSiteWhenDone: function (gotoSiteWhenDone) {
        if (arguments.length > 0) {
            this._gotoSiteWhenDone = gotoSiteWhenDone;
        } else {
            return this._gotoSiteWhenDone;
        }
    },
    addQuestionTextOverride: function (questionID, questionText) {
        this._questionTextOverride[questionID] = questionText;
    },
    addResponseTextOverride: function (questionID, responseID, responseText) {
        if (this._responseTextOverride[questionID] == undefined || this._responseTextOverride[questionID] == null) {
            this._responseTextOverride[questionID] = {};
        }
        this._responseTextOverride[questionID][responseID] = responseText;
    },
    excludeResponse: function (questionID, responseID) {
        if (this._responseExclusions[questionID] == undefined || this._responseExclusions[questionID] == null) {
            this._responseExclusions[questionID] = {};
        }
        this._responseExclusions[questionID][responseID] = true;
    },
    loadQuestions: function () {
        try {
            this.SiteId(PeopleMedia.CP.SiteID());

            // determine panel count
            for (var i = 1; i <= 30; ++i) {
                if ($jq('#divProfileQuestions_' + i.toString()).length > 0) {
                    this.PanelCount(i);
                } else {
                    break;
                }
            }

            this.reset();
            var thisObj = this;
            this.retrieveStandardQuestions(
                function (standardQuestions) {
                    thisObj._questions = [];
                    for (var initialIndex = 0; initialIndex < thisObj._initialQuestions.length; ++initialIndex) {
                        thisObj._questions[initialIndex] = thisObj._initialQuestions[initialIndex];
                    }
                    for (var standardIndex = 0; standardIndex < standardQuestions.length; ++standardIndex) {
                        if ($jq.inArray(standardQuestions[standardIndex].QuestionID, thisObj._excludedQuestions) < 0) {
                            thisObj._questions.push(standardQuestions[standardIndex]);
                        }
                    }
                    for (var questionIndex = 0; questionIndex < thisObj._questions.length; ++questionIndex) {
                        thisObj._questions[questionIndex].QuestionNumber = questionIndex + 1;
                        thisObj.addQuestionHTMLToPanel(thisObj._questions[questionIndex], questionIndex);
                        thisObj.updateQuestionPlaceholder(thisObj._questions[questionIndex]);
                    }
                    thisObj.showPanel(1);
                    var onQuestionsLoaded = thisObj.OnQuestionsLoaded();
                    if (onQuestionsLoaded != undefined && onQuestionsLoaded != null) {
                        onQuestionsLoaded(thisObj, thisObj._questions);
                    }
                },
                function (errors) {
                    var firstError = PeopleMedia.CP.getFirstError(errors);
                    if (firstError && firstError.IsAjaxError) {
                        thisObj.questionsCompleted();
                    } else {
                        PeopleMedia.CP.Messaging.show(errors);
                    }
                });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"loadQuestions" });
        }
    },
    retrieveStandardQuestions: function (onSuccess, onFailure) {
        try {
            var url = PeopleMedia.CP.getPMApiBaseUrl("GetQuestionsAndResponses");
            url += "&communityNameOrID=" + PeopleMedia.CP.SiteID();
            url += "&callbackMethod=?";

            PeopleMedia.CP.ui_busy();

            var thisObj = this;
            var startTime = new Date().getTime();
            var timeoutValue = 30000;
            jQuery.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                success: function (data) {
                    PeopleMedia.CP.ui_done();
                    var errors = [];
                    if (data.Fault) {
                        if (!data.Fault.IsCancelled) {
                            errors.push(PeopleMedia.CP.convertFaultToError(data.Fault));
                        }
                        onFailure(errors);
                    } else {
                        thisObj._standardQuestions = [];
                        for (var i = 0; i < data.length; ++i) {
                            if (data[i].IsSignupQuestion) {
                                thisObj._standardQuestions.push(data[i]);
                            }
                        }
                        thisObj.addInsertedQuestionsToStandardQuestions(data);
                        onSuccess(thisObj._standardQuestions);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                    var errors = [];
                    PeopleMedia.CP.ui_done();
                    if (!data.IsCancelled) {
                        PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "retrieveStandardQuestions", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                        });

                        errors.push(PeopleMedia.CP.convertFaultToError(data.Fault));
                    }
                    onFailure(errors);
                },
                async: true,
                cache: false,
                timeout: timeoutValue
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"retrieveStandardQuestions" });
        }
    },
    addInsertedQuestionsToStandardQuestions: function (data) {
        try {
            var newStandardQuestions;
            var newStandardQuestionsMerged;
            var includedQuestions = this.IncludedQuestions();
            var isFound;
            var insertPosition;
            var insertType;
            var findId;
            if (typeof(data) === 'undefined' || data === null || !$jq.isArray(data) || data.length === 0)
                return;
            if (typeof (includedQuestions) === 'undefined' || includedQuestions === null || $jq.isArray(includedQuestions) === false || includedQuestions.length === 0)
                return;

            // assign data values for inserted questions
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < includedQuestions.length; j++) {
                    if (data[i].QuestionID === includedQuestions[j].QuestionID) {
                        includedQuestions[j].data = data[i];
                        includedQuestions[j].data.IsSignupQuestion = true;
                        break;
                    }
                }
            }
            this.IncludedQuestions(includedQuestions);

            // remove any inserted questions from newStandardQuestions to prevent duplicates
            // create a copy of this._standardQuestions in case there is an exception
            newStandardQuestions = [];
            for (var i = 0; i < this._standardQuestions.length; i++) {
                isFound = false;
                for (var j = 0; j < includedQuestions.length; j++) {
                    if (this._standardQuestions[i].QuestionID === includedQuestions[j].QuestionID) {
                        isFound = true;
                        break;
                    }
                }
                if (!isFound) {
                    newStandardQuestions.push(this._standardQuestions[i]);
                }
            }

            // merge arrays
            for (var i = 0; i < includedQuestions.length; i++) {
                if (includedQuestions[i] && includedQuestions[i].data) {
                    if (typeof (includedQuestions[i].Position) !== 'undefined' && includedQuestions[i].Position >= 0) {
                        insertType = "before";
                        insertPosition = includedQuestions[i].Position;
                        findId = -1;
                    } else if (typeof (includedQuestions[i].InsertBeforeQuestionID) !== 'undefined' && includedQuestions[i].InsertBeforeQuestionID > 0) {
                        insertType = "before";
                        insertPosition = -1;
                        findId = includedQuestions[i].InsertBeforeQuestionID;
                    } else if (typeof (includedQuestions[i].InsertAfterQuestionID) !== 'undefined' && includedQuestions[i].InsertAfterQuestionID > 0) {
                        insertType = "after";
                        insertPosition = -1;
                        findId = includedQuestions[i].InsertAfterQuestionID;
                    } else {
                        insertType = "after";
                        insertPosition = -1;
                        findId = -1;
                    }

                    // do we need to search for an insert position?
                    if (findId > 0) {
                        // special case for question id 999 since it is not in the standard list but appears at the beginning
                        if (findId === 999) {
                            insertType = "before";
                            insertPosition = 0;
                        } else {
                            for (var j = 0; j < newStandardQuestions.length; j++) {
                                if (newStandardQuestions[j].QuestionID === findId) {
                                    insertPosition = j;
                                    break;
                                }
                            }
                        }
                    }

                    // if insertType is before but the item is not found then add it to the beginning
                    if (insertPosition < 0 && insertType === "before") {
                        insertPosition = 0;
                    }

                    // we have a position, now add it to the correct place
                    if (insertPosition >= 0 && insertPosition < newStandardQuestions.length) {
                        newStandardQuestionsMerged = [];
                        for (var j = 0; j < newStandardQuestions.length; j++) {
                            if (insertType === "before" && j === insertPosition) {
                                newStandardQuestionsMerged.push(includedQuestions[i].data);
                            }
                            newStandardQuestionsMerged.push(newStandardQuestions[j]);
                            if (insertType !== "before" && j === insertPosition) {
                                newStandardQuestionsMerged.push(includedQuestions[i].data);
                            }
                        }
                        newStandardQuestions = newStandardQuestionsMerged;
                    } else {
                        // append to the end
                        newStandardQuestions.push(includedQuestions[i].data);
                    }
                }
            }

            this._standardQuestions = newStandardQuestions;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "addInsertedQuestionsToStandardQuestions" });
        }
    },
    submit: function () {
        try {
            if (this._onQuestionsPreSubmit != undefined && this._onQuestionsPreSubmit != null) {
                var cont = this._onQuestionsPreSubmit(this, this.Questions());
                if (!cont) {
                    return;
                }
            }
            if (this.Questions() == null || PeopleMedia.CP.MemberID() == null || PeopleMedia.CP.MemberID() <= 0) {
                return;
            }
            var questionResponseString = "";
            for (var i = 0; i < this.StandardQuestions().length; ++i) {
                if ($jq("#" + this.ResponseFieldnamePrefix() + this.StandardQuestions()[i].QuestionID).length > 0) {
                    var val = $jq("#ddlProfileResponse_" + this.StandardQuestions()[i].QuestionID).val();
                    if (val != undefined && val != null && val.toString().length > 0) {
                        if (questionResponseString.length > 0) {
                            questionResponseString += ",";
                        }
                        questionResponseString += this.StandardQuestions()[i].QuestionID.toString() + "=" + $jq("#ddlProfileResponse_" + this.StandardQuestions()[i].QuestionID).val();
                    }
                }
            }
            this.enterBusyMode();
            var thisObj = this;
            this.submitResponses(
                questionResponseString,
                function (response) {
                    thisObj.exitBusyMode();
                    thisObj.questionsCompleted();
                },
                function (errors) {
                    thisObj.exitBusyMode();
                    var firstError = PeopleMedia.CP.getFirstError(errors);
                    if (firstError && firstError.IsAjaxError) {
                        thisObj.questionsCompleted();
                    } else {
                        PeopleMedia.CP.Messaging.show(errors);
                    }
                });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"submit" });
        }
    },
    submitResponses: function (questionResponseString, onSuccess, onFailure) {
        try {
            var url = PeopleMedia.CP.getPMApiBaseUrl("UpdateQuestionsAndResponsesForMemberBasic");
            url += "&communityName=" + PeopleMedia.CP.SiteID();
            url += "&memberID=" + PeopleMedia.CP.MemberID();
            url += "&questionResponses=" + questionResponseString;
            url += "&callbackMethod=?";

            PeopleMedia.CP.ui_busy();

            var thisObj = this;
            var startTime = new Date().getTime();
            var timeoutValue = 60000;
            jQuery.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                success: function (data) {
                    PeopleMedia.CP.ui_done();
                    var errors = [];
                    if (data.Fault) {
                        if (!data.Fault.IsCancelled) {
                            errors.push(PeopleMedia.CP.convertFaultToError(data.Fault));
                        }
                        onFailure(errors);
                    } else {
                        onSuccess(data);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                    PeopleMedia.CP.ui_done();
                    var errors = [];
                    if (!data.IsCancelled) {
                        PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "submitResponses", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                        });

                        errors.push(PeopleMedia.CP.convertFaultToError(data.Fault));
                    }
                    onFailure(errors);
                },
                async: true,
                cache: false,
                timeout: timeoutValue
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"submitResponses" });
        }
    },
    reset: function () {
        try {
            this._questions = [];
            this._standardQuestions = [];
            if (this._initialQuestions == undefined || this._initialQuestions == null) {
                this._initialQuestions = [];
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"reset" });
        }
    },
    questionsCompleted: function () {
        try {
            if (this._onQuestionsSubmitted != undefined && this._onQuestionsSubmitted != null) {
                this._onQuestionsSubmitted();
            } else if (this.GotoSiteWhenDone() == true) {
                PeopleMedia.CP.gotoSite("/v3/autologin?login=XX" + PeopleMedia.CP.EncodedMemberID() + "&ofp=fse");
            } else if (this.NextPage() != null) {
                PeopleMedia.CP.gotoCPPage(this.NextPage());
            } else {
                PeopleMedia.CP.gotoCPPage("/site/landingpages/shared/essay-02.html");
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "questionsCompleted" });
            PeopleMedia.CP.gotoCPPage("/site/landingpages/shared/essay-02.html");
        }
    },
    addQuestionHTMLToPanel: function (question, index) {
        try {
            if ($jq('#' + this.QuestionContainerId()).length > 0 && $jq('#' + this.QuestionTemplateId()).length > 0) {
                var html = this.getQuestionHTML(question, index);
                $jq('#' + this.QuestionContainerId()).append(html);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"addQuestionHTMLToPanel" });
        }
    },
    getQuestionHTML: function (question, index) {
        try {
            var questionText = question.QuestionText;
            if (this._questionTextOverride[question.QuestionID] != undefined && this._questionTextOverride[question.QuestionID] != null) {
                questionText = this._questionTextOverride[question.QuestionID];
            }

            var html = $jq("#" + this.QuestionTemplateId()).html();
            html = html.replace(/\$QUESTION_NUMBER\$/g, index + 1);
            html = html.replace(/\$QUESTION_ID\$/g, question.QuestionID);
            html = html.replace(/\$QUESTION\$/g, questionText);
            html = html.replace(/\$RESPONSES\$/g, this.getResponseHTML(question));
            return html;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getQuestionHTML" });
            return "";
        }
    },
    getResponseHTML: function (question) {
        if (this._defaultOptionListType == this.OPTION_LIST_TYPE_DIV) {
            return this.getResponseHTML_Div(question);
        } else {
            return this.getResponseHTML_DDL_List(question);
        }
    },
    getResponseHTML_DDL_List: function (question) {
        try {
            // determine size of list, if needed
            var sizeAttr = "";
            if (this._defaultOptionListType == this.OPTION_LIST_TYPE_LIST) {
                var size = 0;
                for (var i = 0; i < question.Responses.length; ++i) {
                    var isExcluded = false;
                    if (this._responseExclusions[question.QuestionID] != undefined && this._responseExclusions[question.QuestionID] != null) {
                        if (this._responseExclusions[question.QuestionID][question.Responses[i].ResponseID] == true) {
                            isExcluded = true;
                        }
                    }
                    if (!isExcluded) {
                        ++size;
                    }
                }

                if (size > this._maxListViewSize) {
                    size = this._maxListViewSize;
                }

                sizeAttr = "size='" + size.toString() + "'";
            }

            // add auto-submit on click
            var onClickAttr = "";
            if (this._defaultOptionListType == this.OPTION_LIST_TYPE_LIST) {
                onClickAttr = "onclick='javascript:PeopleMedia.CP.ProfileManager.getInstance().showNextPanel();return false;'";
            }

            var ddlHtml = "<select id='" + this.ResponseFieldnamePrefix() + question.QuestionID.toString() + "' name='" + this.ResponseFieldnamePrefix() + question.QuestionID.toString() + "' " + sizeAttr + " " + onClickAttr + ">";

            if (this._addChooseOptionToResponses && this._defaultOptionListType != this.OPTION_LIST_TYPE_LIST) {
                ddlHtml += "<option value=''>Choose</option>";
            }

            for (var i = 0; i < question.Responses.length; ++i) {
                var responseText = question.Responses[i].ResponseText;
                if (this._responseTextOverride[question.QuestionID] != undefined && this._responseTextOverride[question.QuestionID] != null) {
                    if (this._responseTextOverride[question.QuestionID][question.Responses[i].ResponseID] != undefined && this._responseTextOverride[question.QuestionID][question.Responses[i].ResponseID] != null) {
                        responseText = this._responseTextOverride[question.QuestionID][question.Responses[i].ResponseID];
                    }
                }
                var isExcluded = false;
                if (this._responseExclusions[question.QuestionID] != undefined && this._responseExclusions[question.QuestionID] != null) {
                    if (this._responseExclusions[question.QuestionID][question.Responses[i].ResponseID] == true) {
                        isExcluded = true;
                    }
                }
                if (!isExcluded) {
                    ddlHtml += "<option value='" + question.Responses[i].ResponseID + "'>" + responseText + "</option>";
                }
            }
            ddlHtml += "</select>";
            return ddlHtml;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getResponseHTML_DDL_List" });
            return "";
        }
    },
    getResponseHTML_Div: function (question) {
        try {
            var onClickAttr = "onclick='javascript:";
            onClickAttr += "$jq(\"#" + this.ResponseFieldnamePrefix() + question.QuestionID.toString() + "\").val(\"##RESPONSEID##\");";
            onClickAttr += "PeopleMedia.CP.ProfileManager.getInstance().showNextPanel();";
            onClickAttr += "return false;'";

            var html = "<input type='hidden' id='" + this.ResponseFieldnamePrefix() + question.QuestionID.toString() + "' name='" + this.ResponseFieldnamePrefix() + question.QuestionID.toString() + "'/>";
            html += "<div class='profileresponsecontainer'>";

            for (var i = 0; i < question.Responses.length; ++i) {
                var responseText = question.Responses[i].ResponseText;
                if (this._responseTextOverride[question.QuestionID] != undefined && this._responseTextOverride[question.QuestionID] != null) {
                    if (this._responseTextOverride[question.QuestionID][question.Responses[i].ResponseID] != undefined && this._responseTextOverride[question.QuestionID][question.Responses[i].ResponseID] != null) {
                        responseText = this._responseTextOverride[question.QuestionID][question.Responses[i].ResponseID];
                    }
                }
                var isExcluded = false;
                if (this._responseExclusions[question.QuestionID] != undefined && this._responseExclusions[question.QuestionID] != null) {
                    if (this._responseExclusions[question.QuestionID][question.Responses[i].ResponseID] == true) {
                        isExcluded = true;
                    }
                }
                if (!isExcluded) {
                    html += "<div id='profileresponse_"+question.QuestionID+"_"+question.Responses[i].ResponseID+"' class='profileresponse' " + onClickAttr.replace('##RESPONSEID##',question.Responses[i].ResponseID) + ">" + responseText + "</div>";
                }
            }

            html += "</div>";
            return html;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getResponseHTML_Div" });
            return "";
        }
    },
    getCurrentQuestionID: function () {
        try {
            var question = this.Questions()[this._currentPanelNumber - 1];
            return question.QuestionID;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getCurrentQuestionID" });
            return "";
        }
    },
    getCurrentQuestionValue: function () {
        try {
            var question = this.Questions()[this._currentPanelNumber - 1];
            return $jq("#" + this.ResponseFieldnamePrefix() + question.QuestionID).val();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getCurrentQuestionValue" });
            return "";
        }
    },
    getCurrentQuestionNumber: function () {
        try {
            var question = this.Questions()[this._currentPanelNumber - 1];
            return question.QuestionNumber;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "getCurrentQuestionNumber" });
            return -1;
        }
    },
    getCurrentResponseID: function() {
        return this.getCurrentQuestionValue();
    },
    updateQuestionPlaceholder: function (question) {
        try {
            if ($jq('#question_' + question.QuestionID).length > 0) {
                $jq('#question_' + question.QuestionID).append(question.QuestionText);
            }
            if ($jq('#response_' + question.QuestionID).length > 0) {
                $jq('#response_' + question.QuestionID).html(this.getResponseHTML(question));
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"updateQuestionPlaceholder" });
        }
    },
    fireOnQuestionDisplay: function () {
        try {
            if (this._onQuestionDisplay != undefined && this._onQuestionDisplay != null) {
                this._onQuestionDisplay();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"fireOnQuestionDisplay" });
        }
    },
    showHideDependentQuestion: function (dependeeQID, dependantQID, exceptionDependeeAnswer, defaultDependantAnswer) {
        try {
            var v = $jq("#response_" + dependeeQID + " > :input").val();
            if (v != undefined && v != null && v.length > 0 && v != exceptionDependeeAnswer) {
                $jq("#divQuestion_" + dependantQID).show();
                $jq("#response_" + dependantQID + " > :input").val("");
            }
            else {
                $jq("#divQuestion_" + dependantQID).hide();
                $jq("#response_" + dependantQID + " > :input").val(defaultDependantAnswer);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showHideDependentQuestion" });
        }
    },
    showNextPanel: function () {
        try {
            var question = this.Questions()[this._currentPanelNumber - 1];
            var val = $jq("#" + this.ResponseFieldnamePrefix() + question.QuestionID).val();
            if (val == undefined || val == null || val.length == 0) {
                PeopleMedia.CP.Messaging.show([{ Text: "Please choose your " + question.QuestionText.replace("_", "") + "."}]);
            }
            else {
                PeopleMedia.CP.Messaging.reset();
                if (this._currentPanelNumber < this._panelCount) {
                    ++this._currentPanelNumber;
                    // handle #children/#livingathome dependency
                    if (question.QuestionID == 16 && (val == 0 || val == "0")) {
                        $jq("#" + this.ResponseFieldnamePrefix() + "17").val("0");
                        ++this._currentPanelNumber;
                    }
                    this.showPanel(this._currentPanelNumber);
                }
                else if (this._currentPanelNumber == this._panelCount) {
                    this.submit();
                }
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showNextPanel" });
        }
    },
    showPreviousPanel: function () {
        try {
            if (this._currentPanelNumber > 1) {
                // handle #children/#livingathome dependency
                if (this._currentPanelNumber > 2) {
                    var question = this.Questions()[this._currentPanelNumber - 3];
                    if (question.QuestionID == 16) {
                        var val = $jq("#" + this.ResponseFieldnamePrefix() + question.QuestionID).val();
                        if (val != undefined && val != null && val.length != 0) {
                            if (val == 0 || val == "0") {
                                --this._currentPanelNumber;
                            }
                        }
                    }
                }
                PeopleMedia.CP.Messaging.reset();
                --this._currentPanelNumber;
                this.showPanel(this._currentPanelNumber);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showPreviousPanel" });
        }
    },
    validatePanel: function (panelNum) {
        try {
            var errors = [];
            var thisObj = this;
            $jq("#divProfileQuestions_" + this._currentPanelNumber.toString() + " select[id^=\"" + this.ResponseFieldnamePrefix() + "\"]").each(function () {
                var questionID = $jq(this).attr('id').substr(thisObj.ResponseFieldnamePrefix().length);
                var question = thisObj.getQuestionByID(questionID);
                if (question != null) {
                    var val = $jq("#" + thisObj.ResponseFieldnamePrefix() + question.QuestionID).val();
                    if (val == undefined || val == null || val.length == 0) {
                        errors.push({ Text: "Please choose your " + question.QuestionText.replace("_", "") + ".", Field: thisObj.ResponseFieldnamePrefix() + question.QuestionID });
                    }
                }
            });
            return errors;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validatePanel" });
            return [];
        }
    },
    validateAndShowPanel: function (panelNum) {
        try {
            var errors = this.validatePanel(panelNum);
            if (errors.length > 0) {
                PeopleMedia.CP.Messaging.show(errors);
            } else {
                this.showPanel(panelNum);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateAndShowPanel" });
        }
    },
    validateAndSubmit: function (panelNum) {
        try {
            var errors = this.validatePanel(panelNum);
            if (errors.length > 0) {
                PeopleMedia.CP.Messaging.show(errors);
            } else {
                this.submit();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateAndSubmit" });
        }
    },
    showPanel: function (panelNum) {
        try {
            PeopleMedia.CP.Messaging.reset();
            if ($jq('#divProfileQuestions_' + panelNum.toString()).length > 0) {
                for (var i = 1; i <= this._panelCount; ++i) {
                    if ($jq('#divProfileQuestions_' + i.toString()).length > 0) {
                        $jq('#divProfileQuestions_' + i.toString()).hide();
                    }
                }
                $jq('#divProfileQuestions_' + panelNum.toString()).show();
                this._currentPanelNumber = panelNum;
                this.fireOnQuestionDisplay();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showPanel" });
        }
    },
    getQuestionByID: function (questionID) {
        try {
            for (var i = 0; i < this._questions.length; ++i) {
                if (this._questions[i].QuestionID == questionID) {
                    return this._questions[i];
                }
            }
            return null;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getQuestionByID" });
            return null;
        }
    },
    getResponseByQuestionID: function (questionID) {
        try {
            var question = this.getQuestionByID(questionID);
            if (typeof(question) !== 'undefined' && question != null) {
                var val = $jq("#" + this.ResponseFieldnamePrefix() + question.QuestionID).val();
                if (typeof(val) !== 'undefined') {
                    return val;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getResponseByQuestionID" });
            return null;
        }
    },
    getResponseSeekingGender: function() {
        try {
            genderResponse = this.getResponseByQuestionID(999);
            if (genderResponse != null && genderResponse.length == 2) {
                return genderResponse.substr(1, 1);
            }
            var genderResponse = this.getResponseByQuestionID(13);
            if (genderResponse != null && genderResponse != '') {
                return (genderResponse == '2') ? '1' : '2';
            }
            return null;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getResponseSeekingGender" });
            return null;
        }	
    },
    enterBusyMode: function () {
        try {
            $jq("." + this.BusyClassname()).each(function () {
                $jq(this).fadeTo('fast', '0.3');
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"enterBusyMode" });
        }
    },
    exitBusyMode: function () {
        try {
            $jq("." + this.BusyClassname()).each(function () {
                $jq(this).fadeTo('fast', '1.0');
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"exitBusyMode" });
        }
    }
};
